"use strict";

var C = require('../common'),
    routers = require('../router'),
    Router = routers.Router,
    RouterWithView = routers.RouterWithView;

module.exports = {

    type: 'prepare',

    load: function (owner, errorController, cb) {

        owner.errorController = function (req, res, error, code, json) {
            errorController = json ? errorController.json : (C._.isString(errorController) ? errorController : errorController.html);
            if (errorController) {
                if (req.router) {
                    if (req.router.forward(errorController, error)) {
                        return true;
                    }
                } else {
                    var info = {
                        controllerPath: errorController,
                        action: code
                    };

                    if (json) {
                        req.router = new Router(owner.route, owner, req, res, info);
                    } else {
                        info.view = errorController + '_' + code;
                        req.router = new RouterWithView(owner.route, owner, req, res, info);
                    }

                    var absControllerPath = owner.toAbsPath(info.controllerPath + '.js');
                    var controller = require(absControllerPath);
                    if (controller[info.action]) {
                        controller[code](req.router, error);
                        return true;
                    }
                }
            }
            
            return false;
        };

        cb();
    }
};